from waveapi import events
from waveapi import model
from waveapi import robot
from waveapi import document

#import gdata.blogger.client
#import gdata.client
#import gdata.sample_util
#import gdata.data
import gdata.alt.appengine
#import atom.data

import gdata.service


def OnRobotAdded(properties, context):
	"""Invoked when the robot has been added."""
	blip = context.GetRootWavelet().CreateBlip()
	waveId = blip.GetWaveId()
	authSubUrl = GetAuthSubUrl(waveId)

	doc = blip.GetDocument()
	
	doc.SetText("\nHello!\n Blogroby helps to embed this wave in your Blogger blog.\n "
		+"First you have to prepare your current template and include below code into head section:\n\n"
		+"<script src=\'http://wave-api.appspot.com/public/embed.js\' type=\'text/javascript\'></script>\n"
		+"<script src=\'http://blogroby.googlecode.com/svn/trunk/embedwave.js\' type=\'text/javascript\'></script>\n\n"
		+"Next, clik below link to authenticate to your Blogger account. Blogroby will create a new draft\n"
		+"with a script that embeds this wave.\n"
		+"To make this wave visible outside participant group add easypublic@appspot.com.\n")
	
	content = doc.GetText(); 
	anchorText = "Click here to authenticate in Blogger."; 
	doc.InsertText(len(content), anchorText)
	start = len(content); 
	end = len(anchorText); 
	doc.SetAnnotation(document.Range(start, start+end), "link/manual",str(authSubUrl)); 
	

def GetAuthSubUrl(waveID):
	next = 'http://blogroby.appspot.com/?waveid='+waveID
	scope = 'http://www.blogger.com/feeds'
	secure = False
	session = True
	blogger_service = gdata.service.GDataService()
	gdata.alt.appengine.run_on_appengine(blogger_service)
	return blogger_service.GenerateAuthSubURL(next, scope, secure, session);	

if __name__ == '__main__':
	myRobot = robot.Robot('blogroby', 
		image_url='http://blogroby.appspot.com/icon.gif',
		version='1',
		profile_url='http://blogroby.appspot.com/')
	myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded)
	myRobot.Run()

